import React, { Component } from 'react';
import {
  WeaLocaleProvider, WeaFormItem, WeaSelect, WeaBrowser, WeaTab, WeaTools, WeaSearchGroup,
} from 'ecCom';
import { WeaTableNew, WeaSwitch } from 'comsMobx';
import { Button } from 'antd';
import './style/updateOperator.less';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';

const { getLabel } = WeaLocaleProvider;
const { WeaTable } = WeaTableNew;

/**
 * 流程动态修改操作者
 * 加操作者，或者减少操作者，或者修改状态
 */
@inject('updateOperatorStore')
@observer
class UpdateOperatorContent extends Component {
  constructor(props) {
    super(props);
    this.tablename = 'operatoredittable';
    this.state = {};
  }

  componentWillMount() {
    if (this.props.visible) {
      this.init();
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.visible != nextProps.visible && nextProps.visible) {
      this.init();
    }
  }

  render() {
    // 第一步
    return (
      <div className={'updateOperatorCotent'}>
        {this.showSelectNodeCom()}
        <div className={'tableOperator'}>
          {this.showEditTableCom()}
        </div>
      </div>
    );
  }

  init = () => {
    const { updateOperatorStore, contentparams } = this.props;
    updateOperatorStore.init(contentparams);
  }

	/**
	 * 可编辑表格组件
	 * @returns {*}
	 */
  showEditTableCom = () => {
    const { updateOperatorStore } = this.props;
    const { coreparams = {}, changeCoreParams, signListStore, reducedSignature, loading = false } = updateOperatorStore;
    const { sltids = [] } = coreparams;
    let btnparams = {
      type: 'primary',
      style: { 'margin-right': '15px' },
      disabled: true,
      onClick: () => reducedSignature({ sltids, showcontent: getLabel(520041, '确定要减去选择的流转吗？') }),
    };
    sltids.length > 0 && !loading && (btnparams.disabled = false);

    let tabparams = {
      datas: [
        {
          title: getLabel(512922, '已设流转'),
          key: '1',
        },
      ],
      keyParam: 'key', // 主键
      className: 'tableOperatorContent',
      searchType: ['advanced'],
      advanceHeight: 120,
      buttons: [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@whhrir@batchReduce`} {...btnparams}>{getLabel(520027, '批量减签')}</Button>,
      ],
      buttonsAd: this.getButtonsAdQuick(),
      showSearchAd: this.state.showSearchAd,
      searchsAd: this.getSearchs(),
      setShowSearchAd: (bool) => {
        this.setState({
          showSearchAd: bool,
        });
      },
    };
    let tableparams = {
      comsWeaTableStore: signListStore,
      hasOrder: true,
      scroll: { y: 300 },
      size: 'small',
      onOperatesClick: this.onOperatesClick,
      rowSelection: {
        onChange: (v, selectdatas) => {
          let sld = [];
          selectdatas.map((item) => {
            sld.push(`${item.id}_${item.isremark}`);
            // sld.push(item.id);
          });
          changeCoreParams({ sltids: sld });
        },
      },
    };
    return (<div>
      <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@imy3w7`} {...tabparams} />
      <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@pt9bwf`} {...tableparams} />
    </div>);
  }

  getButtonsAdQuick = () => {
    const { updateOperatorStore } = this.props;
    const { form, loaddatas } = updateOperatorStore;
    return [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@u9z82l@search`}
        type="primary"
        onClick={() => {
          loaddatas();
          this.setState({ showSearchAd: false });
        }}
      >
        {getLabel(388113, '搜索')}
      </Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qn463t@reset`} type="ghost" onClick={() => { form.resetForm(); }}>
        {getLabel(2022, '重置')}
      </Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@wefxto@cancel`} type="ghost" onClick={() => this.setState({ showSearchAd: false })}>
        {getLabel(201, '取消')}
      </Button>,
    ];
  }

	/**
	 * 高级搜索框信息
	 */
  getSearchs = () => {
    const { updateOperatorStore } = this.props;
    const { condition, form } = updateOperatorStore;
    let groups = [];
    if (form.isFormInit) {
      condition.map((group, index) => {
        groups.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@8m8opm@${index}`}
          needTigger={false}
          // title={group.title}
          showGroup={group.defaultshow}
          items={group.items.map(field => ({
            com: (
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@1kz88s@${field.domkey[0]}`}
                label={field.label}
                labelCol={{ span: field.labelcol }}
                wrapperCol={{ span: field.fieldcol }}
              >
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@ola90p@${field.domkey[0]}`} fieldConfig={field} form={form} />
              </WeaFormItem>
            ),
            col: field.conditionType.toUpperCase() == WeaTools.types.CASCADER ? 1 : 2,
          }))}
        />);
      });
    }
    return groups;
  }

  onOperatesClick = (record, cindex, operate) => {
    const { index } = operate;
    if (index == '0') {
      const { updateOperatorStore } = this.props;
      const { reducedSignature } = updateOperatorStore;
      let sltids = `${record.id}_${record.isremark}`;
      // let sltids = record.id;
      reducedSignature({ sltids, showcontent: getLabel(520042, '确定要减签吗？') });
    }
  }

	/**
	 * 显示当前能控制的节点
	 */
  showSelectNodeCom = () => {
    const items = [];
    const { updateOperatorStore } = this.props;
    const { coreparams = {}, changeSelectNode, changeSelectHrm, selected = {}, loading = false } = updateOperatorStore;
    let { nodeOptions = [] } = coreparams;
    nodeOptions = toJS(nodeOptions);
    items.push(
      <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@z0gi93@next`}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        label={getLabel(512913, '下一环节')}
      >
        <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@sqaqpu@next`}
          options={nodeOptions}
          value={selected.nodeId}
          // options={toJS(nodeOptions)}
          viewAttr={3}
          detailtype={3}
          onChange={(key, value) => {
            changeSelectNode(key, value);
            // this.refs["select_hrm"].set([]);
          }}
        />
      </WeaFormItem>,
    );
    let viewAttr = 3;
		/* if (selected && selected.nodeId) {//节点已选则
				viewAttr = 3;
				//数据筛选
				let sltnode = nodeOptions.filter(item => {
						return item.key == selected.nodeId;
				});
				if (sltnode.length > 0) {
						const {sqlwhereq, sqlwherel} = sltnode[0];
						browserParams.sqlwhere = sqlwhereq;
						completeParams.sqlwhere = sqlwherel;
				}
		} */
    items.push(
      <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ee1zda@selectPeople`}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        label={getLabel(505966, '选择人员')}
      >
        <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@qpix9m@selectPeople`}
          type={17}
          isSingle={false}
          ref={'select_hrm'}
          title={getLabel(505966, '选择人员')}
          onChange={changeSelectHrm}
          hasBorder
          viewAttr={viewAttr}
          maxBrowerHeight={50}
				/* completeParams={{...completeParams}}
				conditionDataParams={{...browserParams}}
				dataParams={{...browserParams}} */
        />
      </WeaFormItem>,
    );

    const { userIds } = selected;
    let btnparams = { disabled: true };
    userIds && !loading && (btnparams.disabled = false);// userIds?disabled:""
    return (<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@b236df`}
      needTigger={true}
      showGroup={true}
      className={'addOperatorSearGroup'}
      title={getLabel(503272, '加签设置')}
      items={[
        {
          com: <div className={'addOperatorContent'}>
            <div className={'addOperator'}>
              {items}
            </div>
            <div className={'addOperatorBtn'}>
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@p698kp@add`} type="primary" {...btnparams} onClick={this.doDirection}>{getLabel(520038, '添加流转')}</Button>
            </div>
          </div>,
          col: 1,
        },
      ]}
    />);
  }

  doDirection = () => {
    const { updateOperatorStore } = this.props;
    const { showConfirm, showErrorMsg, selected = {}, changeSelectHrm } = updateOperatorStore;
    const { userList = [] } = selected;
    if (userList.length <= 0) {
      showErrorMsg(getLabel(385003, '请选择人员'));
      return;
    }

    let allNames = [];
    userList && userList.map((item) => {
      allNames.push(item.lastname);
    });

    let nameStr = '';
    if (allNames.length > 20) {
      nameStr = `${allNames.slice(0, 20).join(',')}...`;
    } else {
      nameStr = allNames.join(',');
    }

    const cssText = 'margin:0 5px; font-weight: bold;color: #2db7f5';
    nameStr = `<span style='${cssText}' title='${allNames.join(',')}'>${nameStr}</span>`;

    let confirmMsg0 = getLabel(513015, '确认将文件发送给$username处理？').replace('$username', nameStr);
    let confirmMsg = (<span
      style={{ 'font-size': '18px' }}
      dangerouslySetInnerHTML={{ __html: confirmMsg0 }}
    />);

    let callback = () => {
      changeSelectHrm(null, null, null);
      // 需要清除人员数据
      this.refs.select_hrm.set([]);
    };

    // 是否确认流转
    showConfirm(null, confirmMsg, () => {
      updateOperatorStore.flowNext(callback);
    });
  }
}
export default UpdateOperatorContent;
